/**
 * The preload script runs before. It has access to web APIs
 * as well as Electron's renderer process modules and some
 * polyfilled Node.js functions.
 *
 * https://www.electronjs.org/docs/latest/tutorial/sandbox
 */
const { contextBridge, ipcRenderer } = require('electron')

window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

console.log(contextBridge)
contextBridge.exposeInMainWorld('versions', {
  node: () => process.versions.node,
  chrome: () => process.versions.chrome,
  electron: () => process.versions.electron,
  ping2: () => ipcRenderer.invoke('ping')
  // 除函数之外，我们也可以暴露变量
})

const _setImmediate = setImmediate
const _clearImmediate = clearImmediate
process.once('loaded', function () {
  console.log('process', process)
  global.setImmediate = _setImmediate
  global.clearImmediate = _clearImmediate
})

contextBridge.exposeInMainWorld('myAPI', {
  desktop: true,
  doAThing: () => {}
})

contextBridge.exposeInMainWorld('electronAPI', {
  setTitle: (title) => ipcRenderer.send('set-title', title),
  openFile: () => ipcRenderer.invoke('dialog:openFile'),
  handleCounter: (callback) => ipcRenderer.on('update-counter', callback)
})
